/*LICENSE_BEGIN
 * ******************************************************************
 * All original parts of SoccerScope2003 have copyright (2003) by
 * Team YowAI, represented by Mr. Shuhei Shiota
 * The Department of Creative Informatics
 * The Graduate School of Information Science and Technology
 * The University of Tokyo
 * 
 * Additional classes (except libraries in /lib) were developed by 
 * the Dainamite Robocup-Team of the DAI-Labor, TU-Berlin 
 * (www.dai-labor.de)
 * 
 * Extended/new classes/packages are:
 *   soccerscope.analyzer.LogfileAnalyzer
 *   soccerscope.daistatistic.*
 *   soccerscope.daistatistic.charts.*
 *   soccerscope.daistatistic.tools.*
 *   soccerscope.db.*
 *   soccerscope.dialog.*
 *   soccerscope.model.PlayerWorldModel
 *   soccerscope.model.SimplePlayer
 *   soccerscope.net.AgentConnector
 *   soccerscope.training.*
 *   soccerscope.training.conditions.*
 * ******************************************************************
LICENSE_END*/
package soccerscope.net;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

public class UDPConnection {
	private final static int BUFFER_SIZE = 2048;

	private byte[] buffer;

	private InetAddress address;

	private int port;

	private DatagramSocket socket;

	public UDPConnection(InetAddress address, int port) {
		this.address = address;
		this.port = port;
		try {
			this.socket = new DatagramSocket();
		} catch (SocketException se) {
			System.err.println(se);
		}
		this.buffer = new byte[BUFFER_SIZE];
	}

	public UDPConnection(String hostname, int port) {
		InetAddress address;
		try {
			address = InetAddress.getByName(hostname);
			this.address = address;
			this.port = port;
			try {
				this.socket = new DatagramSocket();
			} catch (SocketException se) {
				System.err.println(se);
			}
		} catch (UnknownHostException uhe) {
			System.err.println(uhe);
		}
		this.buffer = new byte[BUFFER_SIZE];
	}

	public void send(byte[] msg) {
		// Initilize the packet with data and address
		DatagramPacket packet = new DatagramPacket(msg, msg.length,
				this.address, this.port);
		// send the packet through socket.
		try {
			this.socket.send(packet);
		} catch (IOException ie) {
			System.err.println(ie);
		}
	}

	public void send(String msgString) {
		// Convert the message to an array of bytes
		byte[] message = msgString.getBytes();
		// int msglen = msgString.length();
		send(message);
	}

	public DatagramPacket receive() {
		DatagramPacket packet = new DatagramPacket(this.buffer,
				this.buffer.length);
		// Wait to receive a datagram
		try {
			this.socket.receive(packet);
		} catch (IOException ie) {
			System.err.println(ie);
		}
		return packet;
	}

	public String getHostName() {
		return this.address.getHostName();
	}

	public int getPort() {
		return this.port;
	}
}
